export default function createStore(reducer, enhancer) {
  // enhancer 增强器
  // 其实就是中间件，如果有中间件那么就用中间件把createStore包一层
  if (enhancer) {
    return enhancer(createStore)(reducer);
  }

  let curState = {};
  let curListeners = [];

  function getState() {
    return curState;
  }

  function subscribe(listener) {
    // 只考虑 listener 为函数情况
    curListeners.push(listener);
  }

  function dispatch(action) {
    curState = reducer(curState, action);
    // 执行监听器的每一个函数
    curListeners.map((listener) => listener());

    return action;
  }

  // 初始化执行disptch
  dispatch({
    type: Symbol(),
  });

  return {
    getState,
    subscribe,
    dispatch,
  };
}
